package com.offcn.pay.controller;

import com.alibaba.fastjson.JSON;
import com.offcn.entity.Result;
import com.offcn.entity.StatusCode;
import com.offcn.feign.OrderFeign;
import com.offcn.pay.service.PayService;
import com.offcn.pojo.PayLog;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/pay")
public class PayController {

    @Autowired
    private PayService payService;

    @Autowired
    private OrderFeign orderFeign;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("/createQrCode")
    public Map createQrCode(){
        PayLog payLog = orderFeign.searchPayLogFromRedis().getData();
        if (payLog != null) {
            return payService.createQrCode( payLog.getOutTradeNo(),payLog.getTotalFee() + "");
        }else{
            return new HashMap();
        }
    }
    // 通过消息中间件来创建二维码
    @PostMapping("/createSeckillOrderQrCode")
    public Map createQrCode(@RequestBody Map params){
        return payService.createSeckillOrderQrCode(params);
    }

    /**
     * 该方法是回调方法，支付宝支付成功之后自动调用的方法
     */
    @RequestMapping("/notify")
    public String notifyResult(HttpServletRequest request){
        Map<String, String> map = new HashMap<>();
        Enumeration<String> parameterNames = request.getParameterNames();
        while(parameterNames.hasMoreElements()){
            String element = parameterNames.nextElement();
            String parameteName = element.toString();
            String parameteValue = request.getParameter(parameteName);
            map.put(parameteName,parameteValue);
        }
        String json = JSON.toJSONString(map);
        System.out.println("json:" + json);
        Map<String, String> bodyMap = new HashMap<>();
        //bodyStr => queue=queue.seckillorder&username=offcn001&exchange=exchange.seckillorder&routing=queue.seckillorder&totalAmount=1200
        String bodyStr = map.get("body");
        String[] split = bodyStr.split("&");
        for (String s : split) {
            // s ==> username=offcn001
            String[] kv = s.split("=");
            String key = kv[0];
            String value = kv[1];
            bodyMap.put(key,value);
        }
        // 发送消息
        rabbitTemplate.convertAndSend(bodyMap.get("exchange"),bodyMap.get("routing"),json);
        return "pay-success";
    }

    @RequestMapping("/queryPayStatus")
    public Result queryPayStatus(String out_trade_no){
        int count = 0;
        while(true){
            Map map = payService.queryPayStatus(out_trade_no);
            if (map == null) {
                return new Result(false, StatusCode.ERROR,"支付失败");
            }
            if(map.get("trade_status") != null && map.get("trade_status").equals("TRADE_SUCCESS")){
                System.out.println("支付成功：" + map.get("trade_status") );
                Map payMap = new HashMap<>();
                payMap.put("out_trade_no",out_trade_no);
                payMap.put("trand_no",map.get("trade_no"));
                orderFeign.updateOrderStatus(payMap);
                return new Result(true, StatusCode.OK,"支付成功");
            }
            if(map.get("trade_status") != null && map.get("trade_status").equals("TRADE_CLOSED")){
                System.out.println("支付超时失败：" + map.get("trade_status") );
                return new Result(false,StatusCode.ERROR,"支付超时");
            }
            if(map.get("trade_status") != null && map.get("trade_status").equals("WAIT_BUYER_PAY")){
                System.out.println("正在等待支付：" + map.get("trade_status")  + "----------");
            }
            count++;
            try {
                Thread.sleep(4000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (count >= 30){
                return new Result(false,StatusCode.ERROR,"支付超时，请重新支付");
            }
        }

    }
}
